package com.xuxueli.applyModules.utils.exporttables;

import org.apache.commons.lang3.StringUtils;

import java.sql.*;

/**
 * 连续数据库
 */
public class SqlUtils {

    private static String urls = "jdbc:mysql://localhost:3306?serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=utf8";
    private static String url = "jdbc:mysql://localhost:3306/gaia?serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=utf8";
    static {
        try {
            //Class.forName("com.mysql.jdbc.Driver");
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnnection(String user, String password){
        try {
            return DriverManager.getConnection(SqlUtils.url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Connection getConnnections(String user, String password){
        try {
            return DriverManager.getConnection(SqlUtils.urls, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void closeConnection(Connection conn) throws SQLException {
        if(conn!=null){
            conn.close();
        }
    }

    public static ResultSet getResultSet(Connection conn , String sql){
        try {
            Statement stat = conn.createStatement();
            return stat.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getResultSets(Connection conn , String sql){
        String createTable = StringUtils.EMPTY;
        try {
            PreparedStatement preparedStatement2 = conn.prepareStatement(sql);
            ResultSet resultSet2 = preparedStatement2.executeQuery();
            if(null==resultSet2){
                return createTable;
            }
            while(resultSet2.next()) {
                String tableName = resultSet2.getString("Table");
                createTable = resultSet2.getString("Create Table");
            }
            return createTable;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
